<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="点位" prop="location">
        <el-input
          v-model="queryParams.location"
          placeholder="请输入点位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['campus:machine:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['campus:machine:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['campus:machine:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['campus:machine:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="machineList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键，自增" align="center" prop="id" /> -->
      <el-table-column label="编号" align="center" prop="code" />
      <el-table-column label="点位" align="center" prop="location" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="最大容量" align="center" prop="maxCapacity" />
      <el-table-column label="当前容量" align="center" prop="currentCapacity" />
      <el-table-column label="负责人" align="center" prop="managerId">
        <template slot-scope="scope">
          {{ getUserNameById(scope.row.managerId) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleViewGoods(scope.row)"
            v-hasPermi="['campus:machine:viewGoods']"
          >查看货物</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['campus:machine:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['campus:machine:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改自动售货机对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="点位" prop="location">
          <el-input v-model="form.location" placeholder="请输入点位" />
        </el-form-item>
        <el-form-item label="最大容量" prop="maxCapacity">
          <el-input-number v-model="form.maxCapacity" placeholder="请输入最大容量" controls-position="right" :min="0" style="width: 50%" />
        </el-form-item>
        <!-- <el-form-item label="当前容量" prop="currentCapacity">
          <el-input-number v-model="form.currentCapacity" placeholder="请输入当前容量" controls-position="right" :min="0" style="width: 50%" />
        </el-form-item> -->
        <el-form-item label="货道行数" prop="rowCount">
          <el-input-number v-model="form.rowCount" placeholder="请输入货道行数" controls-position="right" :min="0" style="width: 50%" />
        </el-form-item>
        <el-form-item label="货道列数" prop="columnCount">
          <el-input-number v-model="form.columnCount" placeholder="请输入货道列数" controls-position="right" :min="0" style="width: 50%" />
        </el-form-item>
        <el-form-item label="负责人" prop="managerId">
          <el-select v-model="form.managerId" placeholder="请选择负责人" clearable>
            <el-option
              v-for="user in userList"
              :key="user.userId"
              :label="user.userName"
              :value="user.userId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    
    <!-- 查看货物对话框 -->
    <el-dialog title="货物详情" :visible.sync="goodsOpen" width="60%" append-to-body>
      <div v-loading="goodsLoading">
        <div class="goods-grid">
          <div 
            v-for="(row, rowIndex) in goodsList" 
            :key="rowIndex" 
            class="goods-row">
            <div 
              v-for="(goods, colIndex) in row" 
              :key="colIndex" 
              class="goods-cell">
              <div v-if="goods" class="goods-item">
                <el-image
                  :src="goods.imageUrl"
                  class="goods-image"
                  fit="cover"
                  :preview-src-list="[goods.imageUrl]">
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
                <div class="goods-info">
                  <div class="goods-name">{{ goods.name }}</div>
                  <div class="goods-price">¥{{ goods.price }}</div>
                </div>
                <div class="goods-actions">
                  <el-button size="mini" type="primary" @click="handleEditGoods(goods, rowIndex, colIndex)">修改</el-button>
                  <el-button size="mini" type="danger" @click="handleDeleteGoods(goods, rowIndex, colIndex)">删除</el-button>
                </div>
              </div>
              <div v-else class="empty-goods">
                <div class="empty-placeholder">
                  <i class="el-icon-plus"></i>
                  <div class="empty-text">暂无货物</div>
                </div>
                <div class="goods-actions">
                  <el-button size="mini" type="success" @click="handleAddGoods(rowIndex, colIndex)">新增</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="goodsOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
    
    <!-- 货物操作对话框 -->
    <el-dialog :title="goodsTitle" :visible.sync="goodsFormOpen" width="500px" append-to-body>
      <el-form ref="goodsForm" :model="goodsForm" :rules="goodsRules" label-width="80px">
        <el-form-item label="货物名称" prop="name">
          <el-input v-model="goodsForm.name" placeholder="请输入货物名称" />
        </el-form-item>
        <el-form-item label="货物图片" prop="imageUrl">
          <el-upload
            class="goods-image-uploader"
            action="/dev-api/common/upload"
            :headers="uploadHeaders"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
            :show-file-list="false"
            :disabled="uploadDisabled">
            <img v-if="goodsForm.imageUrl" :src="goodsForm.imageUrl" class="goods-image-preview">
            <i v-else class="el-icon-plus goods-image-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="售价" prop="price">
          <el-input-number v-model="goodsForm.price" placeholder="请输入售价" controls-position="right" :min="0" style="width: 50%" />
        </el-form-item>
        <el-form-item label="位置" prop="position">
          <el-input v-model="goodsForm.position" disabled />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitGoodsForm">确 定</el-button>
        <el-button @click="cancelGoodsForm">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMachine, getMachine, delMachine, addMachine, updateMachine } from "@/api/campus/machine"
import { listUser } from "@/api/system/user"
import { listGoods, addGoods, updateGoods, delGoods } from "@/api/campus/goods"
import { getToken } from "@/utils/auth"

export default {
  name: "Machine",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 自动售货机表格数据
      machineList: [],
      // 用户列表数据
      userList: [],
      // 货物列表数据
      goodsList: [],
      // 最大列数
      maxColumnCount: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示货物弹出层
      goodsOpen: false,
      // 货物加载
      goodsLoading: false,
      // 货物表单标题
      goodsTitle: "",
      // 是否显示货物表单弹出层
      goodsFormOpen: false,
      // 上传图片禁用状态
      uploadDisabled: false,
      // 上传图片headers
      uploadHeaders: { Authorization: "Bearer " + getToken() },
      // 当前选中的售货机
      currentMachine: null,
      // 当前操作类型
      goodsOperType: "",
      // 当前操作的货物位置
      currentGoodsPosition: { rowIndex: 0, colIndex: 0 },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        location: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        location: [
          { required: true, message: "点位不能为空", trigger: "blur" }
        ],
        maxCapacity: [
          { required: true, message: "最大容量不能为空", trigger: "blur" }
        ],
        currentCapacity: [
          { required: true, message: "当前容量不能为空", trigger: "blur" }
        ],
        rowCount: [
          { required: true, message: "货道行数不能为空", trigger: "blur" }
        ],
        columnCount: [
          { required: true, message: "货道列数不能为空", trigger: "blur" }
        ],
        managerId: [
          { required: true, message: "负责人不能为空", trigger: "blur" }
        ],
      },
      // 货物表单参数
      goodsForm: {},
      // 货物表单校验
      goodsRules: {
        name: [
          { required: true, message: "货物名称不能为空", trigger: "blur" }
        ],
        imageUrl: [
          { required: true, message: "货物图片不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "售价不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getUserList()
  },
  methods: {
    /** 查询自动售货机列表 */
    getList() {
      this.loading = true
      listMachine(this.queryParams).then(response => {
        this.machineList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 获取用户列表
    getUserList() {
      listUser({ pageSize: 10000 }).then(response => {
        this.userList = response.rows
      })
    },
    // 根据用户ID获取用户名
    getUserNameById(userId) {
      const user = this.userList.find(item => item.userId === userId)
      return user ? user.userName : userId
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        location: null,
        status: null,
        maxCapacity: null,
        currentCapacity: null,
        rowCount: null,
        columnCount: null,
        managerId: null,
        modifyDate: null,
        createTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加自动售货机"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getMachine(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改自动售货机"
      })
    },
    /** 查看货物按钮操作 */
    handleViewGoods(row) {
      this.currentMachine = row
      this.goodsLoading = true
      this.goodsOpen = true
      listGoods(row.id).then(response => {
        // 根据行列数组织数据
        console.log("后端返回的货物数据:", response);
        const goodsData = response.data || []
        const rowCount = row.rowCount || 0
        const columnCount = row.columnCount || 0
        this.maxColumnCount = columnCount
        
        // 初始化表格数据
        this.goodsList = []
        for (let i = 0; i < rowCount; i++) {
          const rowData = []
          for (let j = 0; j < columnCount; j++) {
            // 根据后端返回的数据结构进行适配
            // 后端返回的数据中没有rowIndex和columnIndex，我们需要根据code字段解析位置
            const goods = goodsData.find(item => {
              // 假设code格式为"{row}-{col}"，例如"1-1"
              if (item.code) {
                const parts = item.code.split('-');
                if (parts.length === 2) {
                  const itemRow = parseInt(parts[0]) - 1; // 转为0基索引
                  const itemCol = parseInt(parts[1]) - 1; // 转为0基索引
                  return itemRow === i && itemCol === j;
                }
              }
              return false;
            });
            
            // 数据字段映射
            if (goods) {
              rowData.push({
                id: goods.id,
                name: goods.name,
                imageUrl: goods.image,
                price: goods.sellingPrice,
                rowIndex: i,
                columnIndex: j,
                code: goods.code
              });
            } else {
              rowData.push(null);
            }
          }
          this.goodsList.push(rowData);
        }
        console.log("处理后的货物列表数据:", this.goodsList);
        this.goodsLoading = false;
      }).catch(error => {
        console.error("获取货物信息失败:", error);
        this.goodsLoading = false;
        this.goodsOpen = false;
        this.$modal.msgError("获取货物信息失败");
      });
    },
    /** 新增货物 */
    handleAddGoods(rowIndex, colIndex) {
      this.goodsOperType = "add";
      this.currentGoodsPosition = { rowIndex, colIndex };
      this.goodsForm = {
        name: undefined,
        imageUrl: undefined,
        price: undefined,
        position: `第${rowIndex + 1}行第${colIndex + 1}列`
      };
      this.goodsTitle = "添加货物";
      this.goodsFormOpen = true;
    },
    /** 修改货物 */
    handleEditGoods(goods, rowIndex, colIndex) {
      this.goodsOperType = "update";
      this.currentGoodsPosition = { rowIndex, colIndex };
      this.goodsForm = {
        id: goods.id,
        name: goods.name,
        imageUrl: goods.imageUrl,
        price: goods.price,
        position: `第${rowIndex + 1}行第${colIndex + 1}列`
      };
      this.goodsTitle = "修改货物";
      this.goodsFormOpen = true;
    },
    /** 删除货物 */
    handleDeleteGoods(goods, rowIndex, colIndex) {
      const position = `第${rowIndex + 1}行第${colIndex + 1}列`;
      this.$modal.confirm(`是否确认删除${position}的货物"${goods.name}"?`).then(() => {
        return delGoods(goods.id);
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
        // 重新加载货物数据
        this.handleViewGoods(this.currentMachine);
      }).catch(() => {});
    },
    /** 图片上传成功处理 */
    handleImageSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.goodsForm.imageUrl = response.fileName;
      } else {
        this.$modal.msgError(response.msg);
      }
      this.uploadDisabled = false;
    },
    /** 图片上传前处理 */
    beforeImageUpload(file) {
      this.uploadDisabled = true;
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$modal.msgError('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$modal.msgError('上传头像图片大小不能超过 2MB!');
      }
      
      if (!isJPG || !isLt2M) {
        this.uploadDisabled = false;
        return false;
      }
      return true;
    },
    /** 货物表单提交 */
    submitGoodsForm() {
      this.$refs["goodsForm"].validate(valid => {
        if (valid) {
          // 构造货物code，格式为"行-列"
          const code = `${this.currentGoodsPosition.rowIndex + 1}-${this.currentGoodsPosition.colIndex + 1}`;
          
          const goodsData = {
            name: this.goodsForm.name,
            image: this.goodsForm.imageUrl,
            sellingPrice: this.goodsForm.price,
            vendingMachineId: this.currentMachine.id,
            code: code
          };
          
          if (this.goodsOperType === "add") {
            addGoods(goodsData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.goodsFormOpen = false;
              // 重新加载货物数据
              this.handleViewGoods(this.currentMachine);
            }).catch(error => {
              console.error("新增货物失败:", error);
              this.$modal.msgError("新增货物失败");
            });
          } else if (this.goodsOperType === "update") {
            goodsData.id = this.goodsForm.id;
            updateGoods(goodsData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.goodsFormOpen = false;
              // 重新加载货物数据
              this.handleViewGoods(this.currentMachine);
            }).catch(error => {
              console.error("修改货物失败:", error);
              this.$modal.msgError("修改货物失败");
            });
          }
        }
      });
    },
    /** 取消货物表单 */
    cancelGoodsForm() {
      this.goodsFormOpen = false;
      this.resetGoodsForm();
    },
    // 货物表单重置
    resetGoodsForm() {
      this.goodsForm = {
        id: null,
        name: undefined,
        imageUrl: undefined,
        price: undefined,
        position: undefined
      };
      this.resetForm("goodsForm");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMachine(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            })
          } else {
            addMachine(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除自动售货机编号为"' + ids + '"的数据项？').then(function() {
        return delMachine(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('campus/machine/export', {
        ...this.queryParams
      }, `machine_${new Date().getTime()}.xlsx`)
    },
    // 表格行样式
    tableRowClassName({row, rowIndex}) {
      return 'goods-row'
    },
    // 计算列宽
    getColumnWidth() {
      // 最小120px，根据列数动态调整
      if (this.maxColumnCount <= 6) {
        return 120
      } else {
        return Math.max(80, 720 / this.maxColumnCount)
      }
    }
  }
}
</script>

<style scoped>
.goods-grid {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.goods-row {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.goods-cell {
  flex: 1;
  min-width: 120px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 8px;
  background-color: #f8f9fa;
  transition: all 0.3s;
}

.goods-cell:hover {
  box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.1);
  background-color: #ffffff;
}

.goods-item {
  text-align: center;
}

.goods-image {
  width: 100%;
  height: 80px;
  border-radius: 3px;
  margin-bottom: 8px;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

.goods-info {
  margin-bottom: 8px;
}

.goods-name {
  font-size: 13px;
  font-weight: 500;
  margin-bottom: 3px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.goods-price {
  font-size: 14px;
  font-weight: bold;
  color: #f56c6c;
}

.empty-goods {
  text-align: center;
  padding: 15px 0;
}

.empty-placeholder {
  margin-bottom: 10px;
}

.empty-placeholder .el-icon-plus {
  font-size: 24px;
  color: #c0c4cc;
  margin-bottom: 3px;
}

.empty-text {
  font-size: 12px;
  color: #909399;
}

.goods-actions {
  display: flex;
  justify-content: center;
  gap: 3px;
}

.goods-actions .el-button {
  font-size: 12px;
  padding: 5px 8px;
  border-radius: 3px;
}

/* 图片上传样式 */
.goods-image-uploader {
  display: block;
}

.goods-image-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  width: 120px;
  height: 120px;
}

.goods-image-uploader .el-upload:hover {
  border-color: #409EFF;
}

.goods-image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.goods-image-preview {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}
</style>